package com.ld.task;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Exchanger;

/**
 * Exchanger:两个线程内的数据交换
 */
public class UseExchange {

    static Exchanger<String[]> exchanger = new Exchanger<>();

    static class ThreadOne implements Runnable {
        @Override
        public void run() {
            String[] list = new String[]{"你好1","你好2","你好3","你好4"};
            try {
                System.out.println("线程"+Thread.currentThread().getName()+"交换之前的数据为"+ Arrays.toString(list));
                list = exchanger.exchange(list);
                System.out.println("线程"+Thread.currentThread().getName()+"交换之后的数据为"+Arrays.toString(list));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class ThreadTwo implements Runnable {
        @Override
        public void run() {
            String[] list = new String[]{"我好1","我好2","我好3","我好4"};
            try {
                System.out.println("线程"+Thread.currentThread().getName()+"交换之前的数据为"+Arrays.toString(list));
                list = exchanger.exchange(list);
                System.out.println("线程"+Thread.currentThread().getName()+"交换之后的数据为"+Arrays.toString(list));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new ThreadOne()).start();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(new ThreadTwo()).start();
    }
}
